var users;
var departments;
$.MvcSheet.Loaded = function () {

    //管理范围内明细表导入数据
    if ($.MvcSheetUI.SheetInfo.ActivityCode == "Activity_Applicant") {
        GetLeader();
        loadUsers();
        loadDepartmentsOf2Level();
    }
    var interval = null;
    $('select[data-datafield="Type"]').change(function () {
        if ($(this).val() !== '项目型') {
            $('input[data-datafield="InternalManagement.Project"],input[data-datafield="ExternalManagement.Project"]').val('').attr('readonly', true);
            interval = setInterval(function () {
                $('input[data-datafield="InternalManagement.Project"],input[data-datafield="ExternalManagement.Project"]').val('').attr('readonly', true);                
            }, 500);
        } else {
            if (interval != null) {
                clearInterval(interval);
                interval = null;
            }
            $('input[data-datafield="InternalManagement.Project"],input[data-datafield="ExternalManagement.Project"]').attr('readonly', false);
        }
    });
};
//上传模板
layui.use('upload', function () {
    var layer = layui.layer;
    var upload = layui.upload;
    upload.render({
        elem: '#exportInternalManagementItems,#exportExternalManagementItems', //绑定元素
        url: $.MvcSheetUI.PortalRoot + "/ImportHandler/ImportHandler", //上传接口
        accept: 'file',
        exts: 'xls',
        data: {},
        done: function (res) {
            if (res.sucess) {
                // debugger;
                var rows = res.data;
                var id = $(this.item).attr('id');

                var xlsres = res.data; // excel 解析结果数组
                var xlsrow ; // 每行数据
                var mycache = []; //ajax 缓存
                var gridDate = [];

                var wlmc;// 物料名称
                for(var j = 0,len = xlsres.length; j < len; j++){
                    // console.log(xlsres[j]);
                   // "10001;qwe;;;;;;;人力资源总监"

                    xlsrow = xlsres[j].split(";");
                    gridDate[j]=xlsrow;

                    //通过物料名称获取其他值
                    if(xlsrow && (wlmc  = xlsrow[1])){
                        var mydata = {};
                        if(!(mycache && mycache[wlmc])){

                            var param = '{"mc":"'+wlmc+'"}';
                            mydata =   getMyGetGridData(param);


                            /* mydata:
                            {
                                "Total": 1,
                                "Rows": [
                                        {
                                            "ObjectID": "a255f50f-1f08-4247-806c-3b7584c67e5d",
                                            "mc": "物料1",
                                            "khbm": "kh001",
                                            "bm": "w001",
                                            "pmbm": "pm001",
                                            "ppbm": "pp001"
                                        }
                                    ]
                            }
                            */

                            if(mydata && mydata["Total"]>0)
                                mycache[j]= mydata["Rows"][0]; //放入缓存
                        }
                    }
                }

                //set gridview
                var rowtitle = [
                                ["bm",// 字段名称
                                    1], // 字段类型 1，string, 2,参与者
                    ["mc",1],["khbm",1],["khmc",1],["ppbm",1],["pp",1],["pric",1],["num",1],["pmbm",1],["pmmc",1],["txsh",1]];
                setMyGridView("bjxq",rowtitle ,gridDate,mycache);




                //插件导入
                /*if (id == 'exportInternalManagementItems') {
                    //插件导入
                    $.importSubTable('InternalManagement', {
                        'InternalManagement.Project': {
                            index: 0//传入数据集的索引列
                        },
                        'InternalManagement.I_ShiX': {
                            index: 1
                        },
                        'InternalManagement.I_JianCR': {
                            index: 2,//传入数据集的索引列
                            type: 1//字段类型,默认0：string，1：multiperson
                        },
                        'InternalManagement.I_ZheRR': {
                            index: 3,
                            type: 1
                        },
                        'InternalManagement.I_FinishTime': {
                            index: 4,
                            type: 2
                        },
                        'InternalManagement.I_Remarks': {
                            index: 5//传入数据集的索引列
                        }
                    }, rows, departments, users);
                } else {//管理范围外数据处理
                    $.importSubTable('ExternalManagement', {
                        'ExternalManagement.Project': {
                            index: 0//传入数据集的索引列
                        },
                        'ExternalManagement.E_ShiX': {
                            index: 1
                        },
                        'ExternalManagement.E_JianCR': {
                            index: 2,//传入数据集的索引列
                            type: 1//字段类型,默认0：string，1：multiperson
                        },
                        'ExternalManagement.E_ZheRDepartment': {
                            index: 3,
                            type: 3
                        },
                        'ExternalManagement.E_FinishTime': {
                            index: 4,
                            type: 2
                        },
                        'ExternalManagement.E_Remarks': {
                            index: 5//传入数据集的索引列
                        }
                    }, rows, departments, users);
                }*/
                layer.msg('导入成功',{time:1000});
            } else {
                layer.msg('上传失败');
            }
        },
        error: function () {
            //请求异常回调
            layer.msg('请求异常回调');
        }
    });
});

function setMyGridView(gridfield,title,xlsdata,mycache){
    if (xlsdata){
        var rowName =gridfield+".";
        var grid =   $.MvcSheetUI.GetSheetDataItem(gridfield, 0);
        var gridNew = $("table[data-datafield="+gridfield+"]").SheetGridView(grid);
        gridNew._Clear();


        for(var i = 0; i<xlsdata.length ;i++){
            gridNew._AddRow();

            var rowdata = xlsdata[i];//每行的值
            var rowcache = mycache[i];

            var celvalue ;
            var gridIndex = i+1;
            for(var j= 0 ;j<title.length;j++){// 给行中的每个表单添加值
                // debugger;
                celvalue ="";
                if (mycache && rowcache[title[j][0]]){
                    if(title[j][1]==1) //string
                        celvalue = rowcache[title[j][0]];
                    else if(title[j][1]==2) // 参与者
                        // 其他类型值预留
                        continue;
                    else
                        continue;
                }else{
                    celvalue = rowdata[j];
                }
                if(celvalue){

                    $.MvcSheetUI.SetControlValue(rowName+title[j][0],	    celvalue,	 gridIndex );
                }

            }


        }




    }






}

function getMyGetGridData(param){
    var result = null;
    //http://localhost:8081/Portal/RunBizQuery/GetGridData
    // schemaCode: slwl
    // queryCode: 商洛物料查询
    // FilterStr: {"mc":"物料1"}
    // PageIndex: 1
    // PageSize: 20

    $.ajax({
        type: "POST",
        url: "/Portal/RunBizQuery/GetGridData/",
        data: {
            "schemaCode": "slwl",
            "queryCode": "商洛物料查询",
            "FilterStr": param,
            "PageIndex": 1,
            "PageSize": 20
        },
        dataType: "json",
        async: false,
        success: function(data) {
            result = data;

            return result;
        }
    })

    return result;

}



function GetLeader() {
    $.MvcSheet.Action(
        {
            Action: "GetApprovalQJ",    // 后台方法名称
            Datas: [$.MvcSheetUI.SheetInfo.Originator],     // 输入参数，格式 ["{数据项名称}","String值","控件ID"]，当包含数据项名称时 LoadControlValue必须为true
            LoadControlValue: true,  // 是否获取表单数据
            PostSheetInfo: false,    // 是否获取已经改变的表单数据
            Async: true,
            OnActionDone: function (e) {
                var val = JSON.parse(e.Calendar);
                // 执行完成后回调事件
                $.MvcSheetUI.SetControlValue("DeptLeader", val.Leader);
            }
        }
    );
}

$.MvcSheet.Submit = function (actionControl, text, destActivity, postValue, groupValue) {
    if (!$.MvcSheet.ActionValidata(actionControl)) return false;
    var items = $.MvcSheetUI.GetControlValue('InternalManagement').length + $.MvcSheetUI.GetControlValue('ExternalManagement').length;
    if (items <= 0) {
        $.ValidationTips.Show(-1, '您需要至少填写1条事项', false);
        setTimeout(hideValidateTips, 3000);
        return false;
    }

    $('input').css('border-color', 'rgb(220, 220, 220)');
    if ($.MvcSheetUI.GetControlValue('Type') === '项目型') {
        var internalTable = $.MvcSheetUI.GetControlValue('InternalManagement');
        for (var i = 0; i < internalTable.length; i++) {
            if (internalTable[i].Project == '') {
                $.ValidationTips.Show(-1, '类型为项目型时，项目必填', false);
                setTimeout(hideValidateTips, 3000);
                $('input[data-datafield="InternalManagement.Project"][data-row="' + (i + 1) + '"]').focus();
                $('input[data-datafield="InternalManagement.Project"][data-row="' + (i + 1) + '"]').css('border', '1px solid red');
                return false;
            }
        }
        var externalTable = $.MvcSheetUI.GetControlValue('ExternalManagement');
        for (var i = 0; i < externalTable.length; i++) {
            if (externalTable[i].Project == '') {
                $.ValidationTips.Show(-1, '类型为项目型时，项目必填', false);
                setTimeout(hideValidateTips, 3000);
                $('input[data-datafield="ExternalManagement.Project"][data-row="' + (i + 1) + '"]').focus();
                $('input[data-datafield="ExternalManagement.Project"][data-row="' + (i + 1) + '"]').css('border', '1px solid red');
                return false;
            }
        }
    }

    var lessCurDate = false;
    //验证完成日期
    $('input[data-datafield="InternalManagement.I_FinishTime"],input[data-datafield="ExternalManagement.E_FinishTime"]').each(function () {
        var thisrow = $(this).data('row');
        var thisfield = $(this).data('datafield');
        var thisvalue = $.MvcSheetUI.GetControlValue(thisfield, thisrow);
        if (new Date(thisvalue) < new Date()) {
            $(this).css('border', '1px solid red');
            $(this).focus();
            $.ValidationTips.Show(-1, '完成时间必须大于当天', false);
            setTimeout(hideValidateTips, 3000);
            lessCurDate = true;
        }
    });
    if (lessCurDate) {
        return;
    }

    //完成验证开始提交
    var that = this;
    $.MvcSheet.ConfirmAction(SheetLanguages.Current.ConfirmDo + "【" + text + "】" + SheetLanguages.Current.Operation + "?", function () {
        $.LoadingMask.Show(SheetLanguages.Current.Sumiting);
        //增加一个提交并确认后的事件，此方法在许多需要与其它系统做集成的时候非常有用；Add by chenghs 2018-07-12
        var callResult = true;
        if ($.isFunction(that.AfterConfirmSubmit)) { //javascript函数
            callResult = that.AfterConfirmSubmit.apply(that);
        } else if (that.AfterConfirmSubmit) { //javascript语句
            callResult = new Function(that.AfterConfirmSubmit).apply(that);
        }
        if (callResult) {
            var SheetPostValue = that.GetMvcPostValue(that.Action_Submit, destActivity, postValue);
            that.PostSheet(
                {
                    Command: that.Action_Submit,
                    MvcPostValue: JSON.stringify(SheetPostValue)
                },
                function (data) {
                    that.ResultHandler.apply(that, [actionControl, data]);
                });
        } else {
            $.LoadingMask.Hide();
        }
    });
};

//生成模板
function generateTemplate(action) {
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + '/ajax/NF_GenerateTemplateHandler.ashx',
        type: 'post',
        data: {
            action: action
        },
        dataType: 'json',
        success: function (data) {
            if (data.errcode === 0)
                window.open($.MvcSheetUI.PortalRoot + data.url);
            else {
                $.ValidationTips.Show(-1, data.errmsg, false);
                setTimeout(hideValidateTips, 3000);
            }

        }
    });
}

//加载所有用户
function loadUsers() {
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + "/ajax/LoadMasterDataHandler.ashx",
        type: "post",
        data: {
            action: 'user'
        },
        dataType: "json",
        async: false,
        success: function (data) {
            users = data;
        }
    });
}
//加载所有二级部门
function loadDepartmentsOf2Level() {
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + "/ajax/LoadMasterDataHandler.ashx",
        type: "post",
        data: {
            action: 'department'
        },
        dataType: "json",
        async: false,
        success: function (data) {
            departments = data;
        }
    });
}
